package com.block.api.controller.source;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.source.service.ISourceApiCheckUserService;
import com.block.source.service.ISourceApiRegisterUserService;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 线索 全流程
 * 需要对接对方文档
 *
 * 上游直接调用该接口，然后根据类型，进行区分处理
 */
@RestController
@RequestMapping("apisourcev1/source")
public class SourceApiSController {

    public static void main(String[] args) {

        String hostUrl = "https://api.longzankeji.cn";
        String hostUrlTest = "http://apitest.koukoudai.shop";
        String onlineCode = "SBJYKH";
        System.out.println("线上撞库地址："+StrUtil.format("{}/apisourcev1/source/checkUser/{}", hostUrl, onlineCode));
        System.out.println("线上进件地址："+StrUtil.format("{}/apisourcev1/source/registerUser/{}", hostUrl, onlineCode));

        String TestCode = "BBZR1L";
        System.out.println("测试撞库地址："+StrUtil.format("{}/apisourcev1/source/checkUser/{}", hostUrlTest, TestCode));
        System.out.println("测试进件地址："+StrUtil.format("{}/apisourcev1/source/registerUser/{}", hostUrlTest, TestCode));

        /**
         * https://api.longzankeji.cn/apinotice/merchant/notifyResult/83
         *
         * https://api.longzankeji.cn/apinotice/merchant/notifyEnter/83
         */
    }
    private static final Logger log = LogFactory.getSourceLog();

//    private final RateLimiter rateLimiter = RateLimiter.create(50);
//
//    private static final List<String> openChannelCode = Collections.unmodifiableList(
//            Arrays.asList("G9BI8M", "QZH60L", "1TJDKW", "SSB093","W8H42D","EPA7PT")
//    );

    @Autowired
    ISourceApiCheckUserService sourceApiCheckUserService;
    @Autowired
    ISourceApiRegisterUserService sourceApiRegisterUserService;

    @RequestMapping(value = "/checkUser/{channelCode}", method = {RequestMethod.POST})
    public String checkUser(HttpServletRequest request,
                            HttpServletResponse httpServletResponse,
                            @PathVariable("channelCode") String channelCode) {

        try {
//            if (!openChannelCode.contains(channelCode)) {
//                boolean limiter = rateLimiter.tryAcquire();
//                if (!limiter){
//                    JSONObject returnObject = new JSONObject();
//                    returnObject.put("code", "500");
//                    returnObject.put("message", "请求频繁，稍后再试");
//                    return returnObject.toJSONString();
//                }
//            }

            Long stattime = System.currentTimeMillis();
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);

            // 线索api 撞库
            JSONObject returnObject = sourceApiCheckUserService.apiCheckUser(channelCode, parameterMap, paramContent, ip);
            Long endtime = System.currentTimeMillis();
            String message = StrUtil.format("【线索api撞库】返回数据展示【channelCode】{}【execTime】{}【returnObject】{}", channelCode, endtime-stattime, JSON.toJSONString(returnObject));
            log.info(message);
            return returnObject.toJSONString();
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "撞库操作异常";
    }



    @RequestMapping(value = "/registerUser/{channelCode}", method = {RequestMethod.POST})
    public String registerUser(HttpServletRequest request,
                               HttpServletResponse httpServletResponse,
                               @PathVariable("channelCode") String channelCode) {

        try {
            Long stattime = System.currentTimeMillis();
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);

            Long endtime = System.currentTimeMillis();
            // 线索api 进件
            JSONObject returnObject = sourceApiRegisterUserService.apiRegisterUser(channelCode, parameterMap, paramContent, ip);
            String message = StrUtil.format("【线索api进件】返回数据展示【channelCode】{}【execTime】{}【returnObject】{}", channelCode, endtime-stattime, JSON.toJSONString(returnObject));
            log.info(message);
            return returnObject.toJSONString();
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "撞库操作异常";
    }

    @RequestMapping(value = "/checkUser1/{channelCode}", method = {RequestMethod.POST})
    public JSONObject checkUse1r(HttpServletRequest request,
                            HttpServletResponse httpServletResponse,
                            @PathVariable("channelCode") String channelCode) {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);

            // 线索api 撞库
            JSONObject returnObject = sourceApiCheckUserService.apiCheckUser(channelCode, parameterMap, paramContent, ip);
            String message = StrUtil.format("【线索api撞库】返回数据展示【channelCode】{}【returnObject】{}", channelCode, JSON.toJSONString(returnObject));
            log.info(message);
            return returnObject;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 500);
        jsonObject.put("message", "撞库操作异常");
        return jsonObject;
    }

    @RequestMapping(value = "/registerUser2/{channelCode}", method = {RequestMethod.POST})
    public JSONObject registerUser2(HttpServletRequest request,
                               HttpServletResponse httpServletResponse,
                               @PathVariable("channelCode") String channelCode) {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);

            // 线索api 进件
            JSONObject returnObject = sourceApiRegisterUserService.apiRegisterUser(channelCode, parameterMap, paramContent, ip);
            String message = StrUtil.format("【线索api进件】返回数据展示【channelCode】{}【returnObject】{}", channelCode, JSON.toJSONString(returnObject));
            log.info(message);
            return returnObject;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 500);
        jsonObject.put("message", "进件操作异常");
        return jsonObject;
    }


    @RequestMapping(value = "/callback1/{channelCode}", method = {RequestMethod.POST})
    public String callback1(HttpServletRequest request,
                               HttpServletResponse httpServletResponse,
                               @PathVariable("channelCode") String channelCode) {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);

            // 线索api 进件
            JSONObject returnObject = sourceApiRegisterUserService.callback1(channelCode, parameterMap, paramContent);
            return returnObject.toJSONString();
        }catch (Exception exception){
            exception.printStackTrace();

        }
        return "申请操作异常";
    }



}